package com.rk.kbk.controller;


import com.alibaba.fastjson.JSONObject;
import com.rk.kbk.common.JsonResp;
import com.rk.kbk.dao.RideTestDao;
import com.rk.kbk.dao.TestDao;
import com.rk.kbk.dao.UserDao;
import com.rk.kbk.dto.PageDto;
import com.rk.kbk.model.RideTest;
import com.rk.kbk.model.Test;
import com.rk.kbk.model.User;
import com.rk.kbk.service.UserService;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.http.MediaType;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import java.util.*;

/**
 * @RideTestController
 * @骑手测试Controller
 * @version : Ver 1.0
 */
@CrossOrigin
@RestController
@Transactional
@RequestMapping(value="/api/rideTest")
public class RideTestController {
    private Logger log = Logger.getLogger(this.getClass());
    @Autowired
    private RideTestDao rideTestDao;
    @Autowired
    private UserDao userDao;
    @Autowired
    private UserService userService;
    @Autowired
    private TestDao testDao;
    @PersistenceContext
    private EntityManager entityManager;

    /**
     * @添加/修改骑手测试
     * @param rideTest
     * @return 返回值JsonResp
     */
    @RequestMapping(value = "/addOrUpdateRideTest",
            method = RequestMethod.POST,
            produces = MediaType.APPLICATION_JSON_VALUE + ";charset=UTF-8")
    public JsonResp addOrUpdateRideTest(@RequestBody RideTest rideTest){
        log.debug("添加/修改骑手测试");
        rideTestDao.save(rideTest);
        return JsonResp.ok();
    }

    /**
     * @骑手测试（提交答卷）
     * @param
     * @return 返回值JsonResp
     */
    @RequestMapping(value = "/submitRideTest",
            method = RequestMethod.POST,
            produces = MediaType.APPLICATION_JSON_VALUE + ";charset=UTF-8")
    public JsonResp submitRideTest(@RequestBody JSONObject jsonObjects ) {
        log.debug("骑手测试（提交答卷）");
        List<RideTest> rideTestList=new ArrayList<>();
        List<Map> maps=(List)jsonObjects.get("rideTest");
        Map map=maps.get(0);
        Map rid=(Map) map.get("ride");
        User ride = userDao.findOne(Long.valueOf(String.valueOf(rid.get("id"))));
            for (Map rideMap : maps) {
                RideTest rideTest=new RideTest();
                Map testMap=(Map) rideMap.get("test");
                Test test=testDao.findOne(Long.valueOf(String.valueOf(testMap.get("id"))));
                if("0".equals(String.valueOf(rideMap.get("id")))){
                    rideTest.setRide(ride);
                    rideTest.setTest(test);
                    rideTest.setStatus(1);
                    rideTest.setSelectOption(String.valueOf(rideMap.get("selectOption")));
                    rideTest.setGetScore(Integer.valueOf(String.valueOf(rideMap.get("getScore"))));
                    rideTest.setIsTrue(Integer.valueOf(String.valueOf(rideMap.get("isTrue"))));
                    rideTestList.add(rideTest);
                }else {
                    RideTest rideTest1=rideTestDao.findOne(Long.valueOf(String.valueOf(rideMap.get("id"))));
                    rideTest1.setRide(ride);
                    rideTest1.setTest(test);
                    rideTest1.setStatus(1);
                    rideTest1.setSelectOption(String.valueOf(rideMap.get("selectOption")));
                    rideTest1.setGetScore(Integer.valueOf(String.valueOf(rideMap.get("getScore"))));
                    rideTest1.setIsTrue(Integer.valueOf(String.valueOf(rideMap.get("isTrue"))));
                    rideTestList.add(rideTest1);
                }

            }
            rideTestDao.save(rideTestList);
            return JsonResp.ok("提交成功！");

    }



    /**
     * @骑手测试（重新考试）
     * @param
     * @return 返回值JsonResp
     */
    @RequestMapping(value = "/retryTest",
            method = RequestMethod.GET,
            produces = MediaType.APPLICATION_JSON_VALUE + ";charset=UTF-8")
    public JsonResp retryTest(Long rideId){
        log.debug("骑手测试（重新考试）");
        User ride =userDao.findOne(rideId);
        List<RideTest> rideTestList=rideTestDao.findByRideAndStatus(ride,1);
        List<Map> retryTestMapList=new ArrayList<>();
        for(int i=0,y=rideTestList.size();i<y;i++){
            RideTest rideTest=rideTestList.get(i);
            Test test=rideTest.getTest();
            Map map=new HashMap();
            if(rideTest.getIsTrue()==2){//如果错误
                map.put("title",test.getTitle());
                map.put("rideTestId",rideTest.getId());
                map.put("testId",test.getId());
                map.put("isMore",test.getIsMore());
                map.put("score",test.getScore());
                map.put("isTrue",rideTest.getIsTrue());
                map.put("selectErrOptionList",Arrays.asList(rideTest.getSelectOption().split(",")));//错误选项
                map.put("selectOptionList", Arrays.asList(test.getSelectOption().split(",")));//选项
                map.put("rightOptionList",Arrays.asList(test.getRightOption().split(",")));//正确选项
                retryTestMapList.add(map);
            }
           // rideTest.setStatus(0);//将其状态更改为为正常
        }
     //   rideTestDao.save(rideTestList);//更新数据库数据
        return JsonResp.ok(retryTestMapList);
    }

    /**
     * @骑手测试返回成绩
     * @param
     * @return 返回值JsonResp
     */
    @RequestMapping(value = "/findRideGetScore",
            method = RequestMethod.GET,
            produces = MediaType.APPLICATION_JSON_VALUE + ";charset=UTF-8")
    public JsonResp findRideGetScore(Long rideId) {
        log.debug("骑手测试返回成绩");
        User ride=userDao.findOne(rideId);
        List<RideTest> rideTests = rideTestDao.findByRideAndStatus(ride, 1);
        int score = 0, errNums = 0, sucNums = 0;
        for (int i = 0, y = rideTests.size(); i < y; i++) {
            RideTest rideTest = rideTests.get(i);
            if (rideTest.getIsTrue()==1) {//如果答案正确
                sucNums += 1;
                score += rideTest.getGetScore();
            } else {
                errNums += 1;
            }
        }
        if(errNums==0){//全对
            ride.setIsTest(1);//通过考试
            userDao.save(ride);
        }else {
            ride.setIsTest(0);//没有通过考试
            userDao.save(ride);
        }
        Map map = new HashMap();
        map.put("score", score);
        map.put("errNums", errNums);
        map.put("sucNums", sucNums);
        return JsonResp.ok(map);
    }








    /**
     * @批量添加/修改骑手测试
     * @param rideTests
     * @return 返回值JsonResp
     */
    @RequestMapping(value = "/addOrUpdateSomeRideTest",
            method = RequestMethod.POST,
            produces = MediaType.APPLICATION_JSON_VALUE + ";charset=UTF-8")
    public JsonResp addOrUpdateSomeRideTest(@RequestBody List<RideTest> rideTests){
        log.debug("批量添加/修改骑手测试");
        rideTestDao.save(rideTests);
        return JsonResp.ok();

    }

    /**
     * @获取骑手测试详情-ByRideTestId
     * @param rideTestId
     * @return 返回值JsonResp
     */
    @RequestMapping(value = "/rideTestDetails",
            method = RequestMethod.GET,
            produces = MediaType.APPLICATION_JSON_VALUE + ";charset=UTF-8")
    public JsonResp findRideTestDetailsByRideTestId(Long rideTestId) {
        log.debug("获取骑手测试详情-ByRideTestId");
        return JsonResp.ok(rideTestDao.findOne(rideTestId));
    }

    /**
     * @分页查询骑手测试(jpa方式)
     * @param rideTest 分页条件
     * @param pageNum 第几页
     * @param pageSize 每页的条数
     * @return 返回值JsonResp
     */
    @RequestMapping(value = "/jpa/page",
            method = RequestMethod.POST,
            produces = MediaType.APPLICATION_JSON_VALUE + ";charset=UTF-8")
    public JsonResp findPageRideTestJpa(@RequestBody(required = false) RideTest rideTest, Integer pageNum, Integer pageSize) {
        log.debug("分页查询骑手测试(jpa方式)");
        //多条件排序Sort
        //Sort sort = new Sort(Sort.Direction.DESC, "createdate").and(new Sort(Sort.Direction.AES, "id"));
        //排序Sort
        Sort sort = new Sort(Sort.Direction.DESC, "gmtDatetime");
        Pageable pageable = new PageRequest(pageNum-1, pageSize, sort);
        Page page = null;
        if (null == rideTest) {
            page = rideTestDao.findAll(pageable); //无条件分页
        }/*else{
            final String condition =  rideTest.getUserName();
            page = rideTestDao.findAll( 		  //条件分页
                    (root, criteriaQuery, cb) -> {
                        Predicate predicate = cb.conjunction();
                        List<Expression<Boolean>> expressions = predicate.getExpressions();
                        if (StringUtils.isNotBlank(condition)) {
                            expressions.add(cb.like(root.<String>get("condition"), "%"+ condition +"%"));
                        }
                        return predicate;
                    }, pageable);
        }*/
//        List<RideTest> content = page.getContent();
//        for (RideTest rideTest1 : content) {
//        }
        return JsonResp.ok(new PageDto(page));
    }

    /**
     * @删除骑手测试-one(永久)
     * @param rideTestId
     * @return 返回值JsonResp
     */
    @RequestMapping(value = "/deleteRideTestOne",
            method = RequestMethod.GET,
            produces = MediaType.APPLICATION_JSON_VALUE + ";charset=UTF-8")
    public JsonResp deleteRideTestOne(Long rideTestId) {
        log.debug("删除骑手测试-one(永久)");
        rideTestDao.delete(rideTestId);
        return JsonResp.ok();
    }

    /**
     * @批量删除骑手测试(永久)
     * @param rideTests
     * @return 返回值JsonResp
     */
    @RequestMapping(value = "/deleteSomeRideTest",
            method = RequestMethod.POST,
            produces = MediaType.APPLICATION_JSON_VALUE + ";charset=UTF-8")
    public JsonResp deleteSomeRideTest(@RequestBody List<RideTest> rideTests) {
        log.debug("批量删除骑手测试(永久)");
        rideTestDao.delete(rideTests);
        return JsonResp.ok();
    }


}
